#include "graphwidget.h"
#include "edge.h"
#include "node.h"
#include "agent.h"
#include "semaphore.h"
#include "traffic_sim.h"
#include <iostream>
#include <QApplication>
#include <QGraphicsScene>
#include <QPushButton>
#include <QLayout>
#include <QPainter>
#include <QPrinter>


using namespace std;


GraphWidget::GraphWidget()
{
  scene = new QGraphicsScene(this);
  scene->setItemIndexMethod(QGraphicsScene::NoIndex);
  scene->setSceneRect(0, 0, 100, 100);
  setScene(scene);
  setCacheMode(CacheBackground);
  setRenderHint(QPainter::Antialiasing);
  setTransformationAnchor(AnchorUnderMouse);
  setResizeAnchor(AnchorViewCenter);
  QGraphicsItem *pixmap = scene->addPixmap(QPixmap("m360.png"));
  pixmap->setPos(-1000,-400);
  pixmap->scale(2.8,2.8);
  scale(0.5, 0.5);
  setMinimumSize(1024, 600);
  setWindowTitle(tr("Simulation Agent Graph"));

}

GraphWidget::GraphWidget(const GraphWidget &g )
{ 
scene=g.scene;
}

Node * GraphWidget::addNode(Traffic_Sim::Traffic_Node_Info & info)
{
  Node *node = new Node(this, info);
  scene->addItem(node); 
  nodeList << node;
  update();
  return node;
}

Agent * GraphWidget::addAgent(Traffic_Sim::Traffic_Vehicle * vehicle)
{
  Agent *agent = new Agent(this, vehicle);
scene->addItem(agent); 
update();

return agent;
}

Node * GraphWidget::searchNode(Traffic_Sim::Traffic_Node_Info & info)
{
 for (int i = 0; i < nodeList.size(); ++i)
 {
     if (nodeList[i]->info.description==info.description)
	{
		return nodeList[i];
	}
 }
return addNode(info);
}


Node * GraphWidget::searchNode1(Traffic_Sim::Traffic_Node_Info & info)
{
 for (int i = 0; i < nodeList.size(); ++i)
 {
     if (nodeList[i]->info.description==info.description)
	{
		return nodeList[i];
	}
 }
return NULL;
}




void GraphWidget::addEdge(Node * n1, Node * n2,Traffic_Sim::Traffic_Arc_Info & info_arc)
{
  Edge *edge= new Edge(n1,n2, info_arc);
  scene->addItem(edge);

}

void GraphWidget::scaleView(qreal scaleFactor)
 {
     qreal factor = matrix().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width();
     if (factor < 0.07 || factor > 100)
         return;

     scale(scaleFactor, scaleFactor);
 }



void GraphWidget::keyPressEvent(QKeyEvent *event)
 {
   
    
 if(Qt::Key_Plus){
cout<<"+"<<endl;     
    scaleView(1.2);
      }else {
cout<<"-"<<endl;
        scaleView(0.8);
     }

  }
    




